package com.youlu.campus.service.activity;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.youlu.campus.entity.OrderInfo;
import com.youlu.campus.entity.UniversityInfo;
import com.youlu.campus.entity.UserParticipateActivityInfo;
import com.youlu.campus.entity.VO.res.ExportUserSignUpResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ExportUserSignUpService {

    @Autowired
    private MongoTemplate mongoTemplate;


    public void exportSignUP(String areaUniversity) {
        if (StringUtils.isBlank(areaUniversity)) {
            log.error("参数未空");
            return;
        }
        Query query = new Query();
        Pattern pattern = Pattern.compile("^.*" + areaUniversity + ".*$", Pattern.CASE_INSENSITIVE);
        query.addCriteria(Criteria.where("name").regex(pattern));
        List<UniversityInfo> universityList = this.mongoTemplate.find(query, UniversityInfo.class);
        if (CollectionUtils.isEmpty(universityList)) {
            log.error("未找到需要导出信息区域所在学校 university -> {}", areaUniversity);
            return;
        }
        query = new Query();
        query.addCriteria(Criteria.where("universityId").in(universityList.stream().map(UniversityInfo::getId).collect(Collectors.toList())));
        List<UserParticipateActivityInfo> userSignUpList = this.mongoTemplate.find(query,
                UserParticipateActivityInfo.class);
        if (CollectionUtils.isEmpty(userSignUpList)) {
            log.error("未找到需要导出信息报名信息 university -> {}", areaUniversity);
            return;
        }
        log.info("开始导出信息报名信息 start -> {}", areaUniversity);
        List<ExportUserSignUpResponse> exportList = new LinkedList<>();
        Map<String, List<UserParticipateActivityInfo>> userMap =
                userSignUpList.stream().collect(Collectors.groupingBy(userParticipateActivityInfo -> userParticipateActivityInfo.getUserId() + "-" + userParticipateActivityInfo.getUniversityId()));
        userMap.forEach((user, item) -> {
            UserParticipateActivityInfo userInfo = item.get(0);
            ExportUserSignUpResponse exportUserSignUp = new ExportUserSignUpResponse();
            exportUserSignUp.setName(userInfo.getName());
            exportUserSignUp.setMobile(userInfo.getMobile());
            exportUserSignUp.setUniversity(userInfo.getUniversityName());
            int size = item.stream().collect(Collectors.groupingBy(UserParticipateActivityInfo::getActivityId)).size();
            exportUserSignUp.setJoinCount(size);
            Query queryOrder = new Query();
            queryOrder.addCriteria(Criteria.where("accountInfoId").is(userInfo.getUserId()));
            queryOrder.addCriteria(Criteria.where("status").nin("0"));
            long count = this.mongoTemplate.count(queryOrder, OrderInfo.class);
            exportUserSignUp.setPlaceOrderCount((int)count);
            exportList.add(exportUserSignUp);
        });
        //写入文件流中
        if(CollectionUtils.isEmpty(exportList)){
            return;
        }
        ExcelWriter excelWriter = null;
        String fileName = "北京学校用户" +"-"+System.currentTimeMillis() + ExcelTypeEnum.XLSX.getValue();
        String file = "/data/app/file/" + fileName;
        try {
            excelWriter = EasyExcel.write(file, ExportUserSignUpResponse.class).build();
            //同一个sheet只要创建一次
            WriteSheet writeSheet = EasyExcel.writerSheet("").build();
            excelWriter.write(exportList, writeSheet);
        }catch (Exception e){
            log.error("导出信息报名信息错误", e);
        }finally {
            if (Objects.nonNull(excelWriter)) {
                excelWriter.finish();
            }
        }
        universityList.clear();
        userSignUpList.clear();
        userMap.clear();
        log.info("结束导出信息报名信息 end -> {}", areaUniversity);


    }


}
